package com.fc.advbox.controller.api;

import com.alibaba.fastjson.JSONObject;
import com.fc.advbox.common.ResponseJson;
import com.fc.advbox.controller.admin.BaseController;
import com.fc.advbox.dto.org.OrgDetailRespDto;
import com.fc.advbox.dto.org.OrgRequest;
import com.fc.advbox.entity.AdvOrgAcctEntity;
import com.fc.advbox.entity.AdvOrgAcctTxnEntity;
import com.fc.advbox.entity.AdvOrgEntity;
import com.fc.advbox.service.IOrgAcctService;
import com.fc.advbox.service.IOrgService;
import com.fc.advbox.utils.Constant;
import com.fc.advbox.utils.PageUtils;
import com.fc.advbox.utils.Query;
import com.fc.advbox.utils.validator.ValidatorUtils;
import com.fc.advbox.utils.validator.group.AddGroup;
import com.fc.advbox.utils.validator.group.UpdateGroup;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * AdvOrgController
 *
 * @author Gary.Jiang
 * @date 2018/6/20.18:33
 */
@RestController
@RequestMapping("/api/org")
@Api(value="机构组织接口", tags={"机构组织接口"})
@Slf4j
public class AdvOrgController extends BaseController {

    @Autowired
    private IOrgService orgService;

    @Autowired
    private IOrgAcctService orgAcctService;


    /**
     * 所有机构组织列表
     */
    @PostMapping("/list")
    @ApiOperation(value = "查询机构组织列表", httpMethod="POST",
            notes = " REST 方式请求," +
                    "Request Params: <ul>" +
                    "<li><i>默认参数: page: 1, 当前页，默认值1 </i></li>" +
                    "<li><i>默认参数: limit: 10 </i></li>" +
                    "<li><i>可选参数: orgType: string, 机构类型, OWNER=管理公司, AGENT=代理商, CHANNEL=渠道商, RENT=广告商 </i></li>" +
                    "<li><i>可选参数: name: string </i></li>" +
                    "<li><i>可选参数: orgCode: string, 机构代码 </i></li>" +
                    "<li><i>可选参数: city: string, 城市 </i></li>" +
                    "<li><i>可选参数: area: string, 地区 </i></li>" +
                    "<li><i>可选参数: createTime, 创建时间, 查询结果大于等于这个时间</i></li>" +
                    "<li><i>可选参数: status: int (0: INACTIVE 1: ACTIVE 2: EXPIRED) </i></li>" +
                    "</ul>")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "body", name = "request", required = true, dataType = "OrgRequest", value="机构组织查询对象"),
    })
    @RequiresPermissions("api:org:view")
    public ResponseJson<PageUtils<AdvOrgEntity>> query(@RequestBody(required = false) OrgRequest request){
        if(request == null){
            request = new OrgRequest();
        }

        Map<String, Object> params = request.toMap();
        //校对并赋值 page和limit
        calculatePagination(params);
        log.info("query org, params:{}", request);
        Query query = new Query(params);
        List<AdvOrgEntity> list = orgService.queryList(params);
        int total = orgService.queryTotal(query);

        PageUtils pageUtil = new PageUtils(list, total, query.getLimit(), query.getPage());
        return ResponseJson.success(pageUtil);
    }

    /**
     * 获取单个机构组织
     */
    @GetMapping("/{id}")
    @ApiOperation(value = "获取单个机构组织", httpMethod="GET" )
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "path", name = "id", required = true, dataType = "long", value="机构组织ID"),
    })
    @RequiresPermissions("api:org:view")
    public ResponseJson<AdvOrgEntity> get(@PathVariable Long id){
        AdvOrgEntity advOrgEntity = orgService.queryObject(id);

        return ResponseJson.success(advOrgEntity);
    }

    /**
     * 获取单个机构组织的资产及收益
     */
    @GetMapping("/{id}/detail")
    @ApiOperation(value = "获取单个机构组织的资产及收益", httpMethod="GET" )
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "path", name = "id", required = true, dataType = "long", value="机构组织ID"),
    })
    @RequiresPermissions("api:org:view")
    public ResponseJson<OrgDetailRespDto> getDetail(@PathVariable Long id){
        OrgDetailRespDto resp = new OrgDetailRespDto();
        AdvOrgEntity org = orgService.queryObject(id);
        resp.setOrg(org);
        List<AdvOrgAcctTxnEntity> txnList = orgAcctService.getAcctTxnByAcctId(org.getAcctId());
        resp.setTxnList(txnList);
//        if(acct.getStatus() != null){
//            if(acct.getStatus()==Constant.StatusDisplay.ENABLE.getValue()){
//                resp.setAcctStatus(Constant.StatusDisplay.ENABLE.getDisplayName());
//            }else if(acct.getStatus()==Constant.StatusDisplay.DISABLE.getValue()){
//                resp.setAcctStatus(Constant.StatusDisplay.DISABLE.getDisplayName());
//            }
//        }
        return ResponseJson.success(resp);
    }

    /**
     * 更新机构组织
     */
    @PutMapping("/update")
    @ApiOperation(value = "更新机构组织", response = ResponseJson.class, httpMethod="PUT",
            notes = " REST 方式请求" +
                    "Request Body: <ul>" +
                    "<li><i>name: 机构组织名称, 必需 </i></li>" +
                    "<li><i>orgCode: 机构代码, 必需 </i></li>" +
                    "<li><i>orgType: 机构类型, 必需 OWNER=管理公司, AGENT=代理商, CHANNEL=渠道商, RENT=广告商 </i></li>" +
                    "<li><i>city: 城市, 必需 </i></li>" +
                    "<li><i>area: 地区 </i></li>" +
                    "<li><i>address: 地址, 必需 </i></li>" +
                    "<li><i>level: 等级 </i></li>" +
                    "<li><i>status: 机构组织状态, 必需, 0: INACTIVE 1: ACTIVE 2: EXPIRED </i></li>" +
                    "<li><i>createTime: 创建时间  格式：yyyy-MM-dd HH:mm:SS 例如 2018-06-19 07:54:01</i></li>" +
                    "<li><i>updateTime: 更新时间  格式：yyyy-MM-dd HH:mm:SS 例如 2018-06-19 07:54:01</i></li>" +
                    "</ul>")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "body", name = "tenant", required = true, dataType = "AdvOrgEntity", value="机构组织对象"),
    })
    @RequiresPermissions("api:org:edit")
    public ResponseJson update(@RequestBody AdvOrgEntity entity){
        if(entity.getUpdateTime() == null){
            entity.setUpdateTime(new Date());
        }
        ValidatorUtils.validateEntity(entity, UpdateGroup.class);

        orgService.update(entity);

        return ResponseJson.success();
    }

    /**
     * 保存机构组织
     */
    @PostMapping("/save")
    @ApiOperation(value = "添加机构组织", response = ResponseJson.class, httpMethod="POST",
            notes = " REST 方式请求" +
                    "Request Body: <ul>" +
                    "<li><i>name: 机构组织名称, 必需 </i></li>" +
                    "<li><i>orgCode: 机构代码, 必需 </i></li>" +
                    "<li><i>orgType: 机构类型, 必需 OWNER=管理公司, AGENT=代理商, CHANNEL=渠道商, RENT=广告商 </i></li>" +
                    "<li><i>city: 城市, 必需 </i></li>" +
                    "<li><i>area: 地区 </i></li>" +
                    "<li><i>address: 地址, 必需 </i></li>" +
                    "<li><i>level: 等级 </i></li>" +
                    "<li><i>status: 机构组织状态, 必需, 0: INACTIVE 1: ACTIVE 2: EXPIRED </i></li>" +
                    "<li><i>createTime: 创建时间  格式：yyyy-MM-dd HH:mm:SS 例如 2018-06-19 07:54:01</i></li>" +
                    "<li><i>updateTime: 更新时间  格式：yyyy-MM-dd HH:mm:SS 例如 2018-06-19 07:54:01</i></li>" +
                    "</ul>")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "body", name = "entity", required = true, dataType = "AdvOrgEntity", value="机构组织对象"),
    })
    @RequiresPermissions("api:org:edit")
    public ResponseJson save(@RequestBody AdvOrgEntity entity){
        if(entity.getCreateTime() == null){
            entity.setCreateTime(new Date());
        }
        if(entity.getUpdateTime() == null){
            entity.setUpdateTime(new Date());
        }
        ValidatorUtils.validateEntity(entity, AddGroup.class);

        orgService.save(entity);

        return ResponseJson.success();
    }

    /**
     * 删除机构组织
     */
    @DeleteMapping("/{id}")
    @ApiOperation(value = "删除机构组织", response = ResponseJson.class, httpMethod="DELETE")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "path", name = "id", required = true, dataType = "long", value="机构组织ID"),
    })
    @RequiresPermissions("api:org:edit")
    public ResponseJson delete(@PathVariable Long id){
        orgService.delete(id);
        return ResponseJson.success();
    }
}
